﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using App.Interface;
using App.Model;
using App.MVC.App_Start;
using App.MVC.Attributes;
using App.MVC.Extend;
using App.MVC.Models;
using Newtonsoft.Json;

namespace App.MVC.Controllers
{
    public class LoginController : Controller
    {
        // GET: Login
        public ILogin _Login { set; get; }
        public IJiaoZhiGong _IJiaoZhiGong { set; get; }
        [AllowAnonymous]
        public ActionResult Index(string returnUrl)
        {

            //ViewBag.ReturnUrl = returnUrl;
            //ViewBa
            return View();
        }
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        [RunningLogAspect(MethodName = "登录提交")]
        [WriteFileExceptionAspect]
        public ActionResult Index(LoginModel model, string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;

            if (string.IsNullOrWhiteSpace(model.UserName) || string.IsNullOrWhiteSpace(model.Password))
            {
                ModelState.AddModelError("", "用户名或密码没有填写");
                return View(model);
            }
            else
            {
                if (_Login.SignIn(model.UserName, model.Password))
                {
                    var trees = _Login.GetMyPowerTree_byusername(model.UserName);
                    trees.SetTrees();
                    model.UserName.SetUserName();
                    var str = _IJiaoZhiGong.GetEmployeebyusername(model.UserName);
                    JiaoZhiGong tt = JsonConvert.DeserializeObject<JiaoZhiGong>(str);
                    tt.XingMing.SetUserXingMing();
                    tt.userinfoId.SetUserId();
                    return RedirectToLocal(string.Equals(returnUrl, "/Login/LogOff", StringComparison.CurrentCultureIgnoreCase) ? "/Home/Index" : returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "提供的用户名或密码不正确。");
                    return View(model);
                }
            }
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
        }
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        [AllowAnonymous]
        public ActionResult LogOff()
        {
            CookieHelper.DelAllCookie();
            return RedirectToAction("Index", "Login");
        }
    }
}